package com.lsp.java.tread.util;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @Description await()    使当前线程进入同步队列进行等待，直到latch的值被减到0或者当前线程被中断，当前线程就会被唤醒。
 * await(long timeout, TimeUnit unit)	带超时时间的await()。
 * countDown()	使latch的值减1，如果减到了0，则会唤醒所有等待在这个latch上的线程。
 * getCount()	获得latch的数值。
 * @Author lishengpeng
 * @Date 2022/8/2 19:42
 */
public class CountDownLatchTest {

    public static final ExecutorService EXECUTOR = new ScheduledThreadPoolExecutor(1,
            new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build());

    public static void main(String[] args) throws InterruptedException {
        // 让2个线程去等待3个三个工作线程执行完成
        CountDownLatch c = new CountDownLatch(3);

        // 2 个等待线程
        WaitThread waitThread1 = new WaitThread("wait-thread-1", c);
        WaitThread waitThread2 = new WaitThread("wait-thread-2", c);

        // 3个工作线程
        Worker worker1 = new Worker("worker-thread-1", c);
        Worker worker2 = new Worker("worker-thread-2", c);
        Worker worker3 = new Worker("worker-thread-3", c);
        EXECUTOR.submit(waitThread1);
        EXECUTOR.submit(waitThread2);
        EXECUTOR.submit(worker1);
        EXECUTOR.submit(worker2);
        EXECUTOR.submit(worker3);
        // 启动所有线程
//        waitThread1.start();
//        waitThread2.start();
//        Thread.sleep(1000);
//        worker1.start();
//        worker2.start();
//        worker3.start();
    }
}
